import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
    //数据，相当于data
    state: {
        user:{
          isLogin:false,
          username:'匿名用户',
        },
        books:[],
        carts:[]
    },
    getters: {
        getTotalPrice(state){
            let totalPrice=0;
            state.carts.forEach(c=>{
                totalPrice+=c.price*c.quantity;
            })
            return totalPrice.toFixed(2);
        }
    },
    //里面定义方法，操作state方发
    mutations: {
        addCart(state,book){
            let cart=state.carts.find(c=>c.ISBN==book.ISBN);
            if(cart){
                if(cart.quantity==cart.inventory){
                    this.$message("书本库存不足");
                }else {
                    cart.quantity++;
                }

            }else {
                console.log(book);
                let cart={...book, quantity:1};
                console.log(cart);
                state.carts.push(cart);
            }
            console.log(state.carts)
        },
        delCart(state,ISBN){
            let cart=state.carts.find(c=>c.ISBN==ISBN);
            let location=state.carts.indexOf(cart);
            state.carts.splice(location,1);
        }
        ,
        changeNum(state,id,num){
            let cart=state.carts.find(c=>c.ISBN==id);
            if(cart.quantity<num){
                if(cart.quantity==cart.inventory){
                    this.$message("书本库存不足");
                }else {cart.quantity++;
                }
            }
            if(cart.quantity>num){
                if(cart.quantity>1){
                    cart.quantity--;
                }else {
                    this.$message("已经只剩1件商品");
                }
            }
        },
        updateProps(state,props){
            state.books=props
            console.log(state.books)
        },
        clearCart(state){
            state.carts=[]
        }
    },
    // 操作异步操作mutation
    actions: {

    },
    modules: {

    },
})
